<?php

namespace app\controllers;

use Yii;
use app\models\Menu;
use Codeception\Util\Uri;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\Url;
use app\commands\Service;

/**
 * MenuController implements the CRUD actions for Menu model.
 */
class MenuController extends Service
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Menu models.
     * @return mixed
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Menu::find(),
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Menu model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * 自动更新菜单数据表
     */
    public function actionAutocreate()
    {
        $controllerlist = [];
        if ($handle = opendir('../controllers')) {
            while (false !== ($file = readdir($handle))) {
                if ($file != "." && $file != ".." && substr($file, strrpos($file, '.') - 10) == 'Controller.php') {
                    $controllerlist[] = $file;
                }
            }
            closedir($handle);
        }
        asort($controllerlist);

        $fulllist = [];
        foreach ($controllerlist as $controller) {
            $handle = fopen('../controllers/' . $controller, "r");
            if ($handle) {
                while (($line = fgets($handle)) !== false) {
                    if (preg_match('/public function action(.*?)\(/', $line, $display)) {
                        if (strlen($display[1]) > 2) {
                            $fulllist[substr($controller, 0, -4)][] = strtolower($display[1]);
                        }
                    }
                }
            }
            fclose($handle);
        }

        $insert_count = 0;

        $controller_dict = [
            'comeway' => '媒体来源',
            'communication' => '咨询途径',
            'department' => '医院科室',
            'disease' => '病种',
            'doctor' => '医生',
            'job' => '职位',
            'log' => '日志',
            'menu' => '菜单',
            'recall' => '回访',
            'sysconfig' => '系统参数',
            'user' => '员工',
            'patient' => '患者',
            'workgroup' => '群组',
            'task' => '任务',
        ];
        $action_dict = [
            'index' => '管理',
            'view' => '详细信息',
            'create' => '新增',
            'update' => '修改',
            'delete' => '删除',
        ];
        if (count($fulllist) > 0) {
            foreach ($fulllist as $c_name => $a_array) {
                if ($c_name == 'site') {
                    continue;
                }
                foreach ($a_array as $a_name) {
                    $c_name = strtolower(str_replace('Controller', '', $c_name));
                    $route = $c_name . '/' . $a_name;
                    $model = Menu::find()->where("url = '{$route}'")->one();
                    if ($model == null) {
                        $model = new Menu();
                        $model->url = $route;
                        $model->name = '页面名称等待修改';
                        if (null != $controller_dict[$c_name] && null != $action_dict[$a_name]) {
                            if ($a_name == 'index' && strlen($action_dict[$a_name]) > 7) {
                                $model->name = $controller_dict[$c_name];
                            } else {
                                $model->name = $controller_dict[$c_name] . '-' . $action_dict[$a_name];
                            }
                        }
                        $model->sort = 100;
                        if ($model->save()) {
                            $insert_count++;
                        }
                    }
                }
            }
        }


        if ($insert_count == 0) {
            return '<script>alert("没有任何controller的action，新插入到菜单数据表");window.location.href="' . Url::toRoute('menu/index') . '"</script>';
        } else {
            return '<script>alert("新插入菜单' . $insert_count . '条");window.location.href="' . Url::toRoute('menu/index') . '"</script>';
        }
    }

    /**
     * Updates an existing Menu model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing Menu model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Menu model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Menu the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Menu::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
